//package com.yt.sys.api.cms;
//
//import com.baomidou.mybatisplus.mapper.EntityWrapper;
//import com.baomidou.mybatisplus.mapper.Wrapper;
//import com.baomidou.mybatisplus.plugins.Page;
//import com.yt.common.constant.Result;
//import com.yt.common.enums.CodeEnum;
//import com.yt.common.utils.StrUtils;
//import com.yt.sys.models.dto.SysPermissionDTO;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiImplicitParam;
//import io.swagger.annotations.ApiImplicitParams;
//import io.swagger.annotations.ApiOperation;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.dubbo.config.annotation.DubboReference;
//import org.springframework.beans.BeanUtils;
//import org.springframework.web.bind.annotation.*;
//import java.util.Arrays;
//import java.util.List;
//import java.util.stream.Collectors;
//
//import com.yt.sys.models.service.ISysRoleService;
//import com.yt.sys.models.bo.SysRoleSaveBO;
//import com.yt.sys.models.bo.SysRoleBO;
//import com.yt.sys.models.dto.SysRoleDTO;
//
///**
// * 权限控制器
// *
// * @author xieyanfei
// * @Date 2025-09-08 11:04:33
// */
//
//@RestController
//@RequestMapping("/cms/sysRole")
//@Slf4j
//@Api(value = "SysRoleController",tags = "权限接口")
//public class SysRoleController {
//
//    @DubboReference
//    private ISysRoleService sysRoleService;
//
//    @ApiOperation(value = "添加权限",notes = "添加权限")
//    @PostMapping(value = "/insert")
//    public Result insert(SysRoleSaveBO saveBO) {
//        boolean flag = sysRoleService.add(saveBO);
//        if (flag){
//            return new Result<>();
//        } else {
//            return new Result<>(CodeEnum.FAIL_100007);
//        }
//    }
//
//    @PostMapping("/save")
//    @ApiOperation(value = "保存权限",notes = "保存权限")
//    public Result save(SysRoleSaveBO saveBO){
//        if(saveBO.getId() == null){
//            //添加
//            return  insert(saveBO);
//        } else {
//            return  update(saveBO);
//        }
//    }
//
//    @ApiOperation(value = "修改权限",notes = "修改权限")
//    @PostMapping("/update")
//    public Result update(SysRoleSaveBO saveBO){
//        SysRoleDTO dto = new SysRoleDTO();
//        BeanUtils.copyProperties(saveBO, dto);
//        dto.setId(saveBO.getId());
//        boolean flag = sysRoleService.updateById(dto);
//        if (flag){
//            return new Result<>();
//        } else {
//            return new Result<>(CodeEnum.FAIL_100008);
//        }
//    }
//
//    @PostMapping("/updateStatus")
//    @ApiOperation(value = "修改状态",notes = "修改状态")
//     @ApiImplicitParams({
//             @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
//             ,@ApiImplicitParam(name = "status",value = "状态(0:禁用,1:启用)",required = true,paramType = "query", dataType = "Integer")
//     })
//     public Result updateStatus(Long id, Integer status){
//         SysRoleDTO dto = new SysRoleDTO();
//         dto.setId(id);
//         dto.setStatus(status);
//        boolean flag = sysRoleService.updateById(dto);
//         if(flag){
//             return new Result<>();
//         } else {
//             return new Result<>(CodeEnum.FAIL_100008);
//         }
//     }
//
//    @ApiOperation(value = "删除权限",notes = "删除权限")
//    @ApiImplicitParam(name = "id",value = "权限id",required = true,paramType = "query",dataType = "Long")
//    @PostMapping("/delete")
//    public Result delete(@RequestParam("id") Long id){
//        boolean flag = sysRoleService.deleteById(id);
//        if (flag){
//            return new Result<>();
//        } else {
//            return new Result<>(CodeEnum.FAIL_100009);
//        }
//    }
//
//    @PostMapping("/deleteBatch")
//    @ApiOperation(value = "批量删除权限",notes = "批量删除权限")
//    @ApiImplicitParam(name = "ids",value = "ids:以逗号隔开",required = true,paramType = "query", dataType = "String")
//    public Result deleteBatch(@RequestParam("ids") String ids){
//        if(StrUtils.isEmpty(ids)){
//            return new Result(CodeEnum.FAIL_100002 );
//        }
//        String[] arr = ids.split(",");
//        sysRoleService.deleteBatchIds(Arrays.asList(arr));
//        return new Result<>();
//    }
//
//    @PostMapping("/get")
//    @ApiOperation(value = "根据id查找",notes = "根据id查找")
//    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
//    public Result<SysRoleDTO> get(@RequestParam("id") Long id){
//        if(id == null){
//            return new Result<>(CodeEnum.FAIL_100002 );
//        }
//
//        SysRoleDTO dto = sysRoleService.selectById(id);
//
//        return new Result<>(dto);
//    }
//
//    @ApiOperation(value = "权限列表",notes = "权限列表")
//    @PostMapping("/queryPageList")
//    public Result<Page<SysRoleDTO>> queryPageList(SysRoleBO bo){
//        Wrapper<SysRoleDTO> wrapper = new EntityWrapper<>();
//
//                if (bo.getStatus() != null){
//                    wrapper.eq("status", bo.getStatus());
//                }
//
//        if (bo.getStartDate() != null){
//            wrapper.ge("create_time", bo.getStartDate());
//        }
//        if (bo.getEndDate() != null){
//            wrapper.le("create_time", bo.getEndDate());
//
//        }
//        Page<SysRoleDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
//        page = sysRoleService.selectPage(page, wrapper);
//
//        return new Result<>(page);
//    }
//    @ApiOperation(value = "获取角色权限", notes = "获取角色拥有的权限列表")
//    @PostMapping("/getRolePermissions")
//    @ApiImplicitParam(name = "roleId", value = "角色ID", required = true, paramType = "query", dataType = "Long")
//    public Result<List<SysPermissionDTO>> getRolePermissions(@RequestParam("roleId") Long roleId) {
//        if (roleId == null) {
//            return new Result<>(CodeEnum.FAIL_100002);
//        }
//        List<SysPermissionDTO> permissions = sysRoleService.getRolePermissions(roleId);
//        return new Result<>(permissions);
//    }
//
//    @ApiOperation(value = "分配权限给角色", notes = "为角色分配权限")
//    @PostMapping("/assignPermissions")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "roleId", value = "角色ID", required = true, paramType = "query", dataType = "Long"),
//            @ApiImplicitParam(name = "permissionIds", value = "权限ID列表，逗号分隔", required = true, paramType = "query", dataType = "String")
//    })
//    public Result assignPermissions(Long roleId, String permissionIds) {
//        if (roleId == null || StrUtils.isEmpty(permissionIds)) {
//            return new Result<>(CodeEnum.FAIL_100002);
//        }
//        List<Long> permissionIdList = Arrays.stream(permissionIds.split(","))
//                .map(Long::parseLong)
//                .collect(Collectors.toList());
//        boolean flag = sysRoleService.assignPermissions(roleId, permissionIdList);
//        return flag ? new Result<>() : new Result<>(CodeEnum.FAIL_100008);
//    }
//}
package com.yt.sys.api.cms;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.common.utils.StrUtils;
import com.yt.sys.models.dto.SysPermissionDTO;
import com.yt.sys.models.dto.SysRoleDTO;
import com.yt.sys.models.dto.SysUserRoleDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.yt.sys.models.service.ISysRoleService;
import com.yt.sys.models.service.ISysUserService;
import com.yt.sys.models.bo.SysRoleSaveBO;
import com.yt.sys.models.bo.SysRoleBO;
import com.yt.sys.utils.PermissionCheckUtil;
import com.yt.sys.mapper.SysUserRoleMapper;

/**
 * 角色管理控制器（含超级管理员权限控制）
 *
 * @author xieyanfei
 * @Date 2025-09-08 11:04:33
 */
@RestController
@RequestMapping("/cms/sysRole")
@Slf4j
@Api(value = "SysRoleController", tags = "角色管理接口")
public class SysRoleController {

    @DubboReference
    private ISysRoleService sysRoleService;

    @DubboReference
    private ISysUserService sysUserService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private PermissionCheckUtil permissionCheckUtil;

    /**
     * 获取当前登录用户ID（实际项目中需从Token或SecurityContext获取）
     * 示例：从请求头或会话中解析用户ID
     */
    private Long getCurrentUserId() {
        // TODO 替换为实际认证逻辑，如：
        // String token = request.getHeader("Authorization");
        // return JwtUtil.getUserId(token);
        return 10004L; // 测试用超级管理员ID（需与数据库中用户ID一致）
    }

    /**
     * 添加角色（需ROLE:ADD权限）
     */
    @ApiOperation(value = "添加角色", notes = "超级管理员或拥有ROLE:ADD权限的用户可操作")
    @PostMapping(value = "/insert")
    public Result insert(@RequestBody SysRoleSaveBO saveBO) {
        Long userId = getCurrentUserId();
        // 权限校验：超级管理员或拥有ROLE:ADD权限
        if (!permissionCheckUtil.hasPermission(userId, "ROLE:ADD")) {
            return new Result<>(CodeEnum.NO_PERMISSION);
        }

        // 校验角色标识唯一性
        SysRoleDTO existRole = sysRoleService.selectOne(
                new EntityWrapper<SysRoleDTO>().eq("role_logo", saveBO.getRoleLogo())
        );
        if (existRole != null) {
            return new Result<>(CodeEnum.FAIL, "角色标识已存在，请更换");
        }

        boolean flag = sysRoleService.add(saveBO);
        return flag ? new Result<>() : new Result<>(CodeEnum.FAIL_100007);
    }

    /**
     * 保存角色（新增或修改）
     */
    @PostMapping("/save")
    @ApiOperation(value = "保存角色", notes = "新增或修改角色")
    public Result save(SysRoleSaveBO saveBO) {
        if (saveBO.getId() == null) {
            // 添加角色（复用insert的权限校验）
            return insert(saveBO);
        } else {
            // 修改角色（复用update的权限校验）
            return update(saveBO);
        }
    }

    /**
     * 修改角色（需ROLE:EDIT权限）
     */
    @ApiOperation(value = "修改角色", notes = "超级管理员或拥有ROLE:EDIT权限的用户可操作")
    @PostMapping("/update")
    public Result update(@RequestBody SysRoleSaveBO saveBO) {
        Long userId = getCurrentUserId();
        // 权限校验：超级管理员或拥有ROLE:EDIT权限
        if (!permissionCheckUtil.hasPermission(userId, "ROLE:EDIT")) {
            return new Result<>(CodeEnum.NO_PERMISSION);
        }

        // 校验角色是否存在
        if (saveBO.getId() == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        SysRoleDTO existRole = sysRoleService.selectById(saveBO.getId());
        if (existRole == null) {
            return new Result<>(CodeEnum.FAIL, "角色不存在");
        }

        // 若修改角色标识，需校验唯一性
        if (!existRole.getRoleLogo().equals(saveBO.getRoleLogo())) {
            SysRoleDTO sameLogoRole = sysRoleService.selectOne(
                    new EntityWrapper<SysRoleDTO>().eq("role_logo", saveBO.getRoleLogo())
            );
            if (sameLogoRole != null) {
                return new Result<>(CodeEnum.FAIL, "角色标识已存在，请更换");
            }
        }

        SysRoleDTO dto = new SysRoleDTO();
        BeanUtils.copyProperties(saveBO, dto);
        dto.setId(saveBO.getId());
        boolean flag = sysRoleService.updateById(dto);
        return flag ? new Result<>() : new Result<>(CodeEnum.FAIL_100008);
    }

    /**
     * 修改角色状态（需ROLE:EDIT权限）
     */
    @PostMapping("/updateStatus")
    @ApiOperation(value = "修改角色状态", notes = "超级管理员或拥有ROLE:EDIT权限的用户可操作")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "角色ID", required = true, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "status", value = "状态(0:禁用,1:启用)", required = true, paramType = "query", dataType = "Integer")
    })
    public Result updateStatus(Long id, Integer status) {
        Long userId = getCurrentUserId();
        // 权限校验：超级管理员或拥有ROLE:EDIT权限
        if (!permissionCheckUtil.hasPermission(userId, "ROLE:EDIT")) {
            return new Result<>(CodeEnum.NO_PERMISSION);
        }

        // 禁止禁用超级管理员角色（避免系统失控）
        if (status == 0) {
            SysRoleDTO role = sysRoleService.selectById(id);
            if (role != null && "ADMIN".equals(role.getRoleLogo())) {
                return new Result<>(CodeEnum.FAIL, "不可禁用超级管理员角色");
            }
        }

        SysRoleDTO dto = new SysRoleDTO();
        dto.setId(id);
        dto.setStatus(status);
        boolean flag = sysRoleService.updateById(dto);
        return flag ? new Result<>() : new Result<>(CodeEnum.FAIL_100008);
    }

    /**
     * 删除角色（需ROLE:DELETE权限）
     */
    @ApiOperation(value = "删除角色", notes = "超级管理员或拥有ROLE:DELETE权限的用户可操作")
    @ApiImplicitParam(name = "id", value = "角色ID", required = true, paramType = "query", dataType = "Long")
    @PostMapping("/delete")
    public Result delete(@RequestParam("id") Long id) {
        Long userId = getCurrentUserId();
        // 权限校验：超级管理员或拥有ROLE:DELETE权限
        if (!permissionCheckUtil.hasPermission(userId, "ROLE:DELETE")) {
            return new Result<>(CodeEnum.NO_PERMISSION);
        }

        // 校验1：角色是否存在
        SysRoleDTO role = sysRoleService.selectById(id);
        if (role == null) {
            return new Result<>(CodeEnum.FAIL, "角色不存在");
        }

        // 校验2：禁止删除超级管理员角色
        if ("ADMIN".equals(role.getRoleLogo())) {
            return new Result<>(CodeEnum.FAIL, "不可删除超级管理员角色");
        }

        // 校验3：禁止删除当前用户关联的角色
        List<SysUserRoleDTO> userRoles = sysUserRoleMapper.selectList(
                new EntityWrapper<SysUserRoleDTO>()
                        .eq("user_id", userId)
                        .eq("role_id", id)
        );
        if (!userRoles.isEmpty()) {
            return new Result<>(CodeEnum.FAIL, "不可删除当前用户关联的角色");
        }

        // 校验4：禁止删除已分配给其他用户的角色
        List<SysUserRoleDTO> allUserRoles = sysUserRoleMapper.selectList(
                new EntityWrapper<SysUserRoleDTO>().eq("role_id", id)
        );
        if (!allUserRoles.isEmpty()) {
            return new Result<>(CodeEnum.FAIL, "该角色已分配给" + allUserRoles.size() + "个用户，不可删除");
        }

        boolean flag = sysRoleService.deleteById(id);
        return flag ? new Result<>() : new Result<>(CodeEnum.FAIL_100009);
    }

    /**
     * 批量删除角色（需ROLE:DELETE权限）
     */
    @PostMapping("/deleteBatch")
    @ApiOperation(value = "批量删除角色", notes = "超级管理员或拥有ROLE:DELETE权限的用户可操作")
    @ApiImplicitParam(name = "ids", value = "角色ID列表（逗号分隔）", required = true, paramType = "query", dataType = "String")
    public Result deleteBatch(@RequestParam("ids") String ids) {
        Long userId = getCurrentUserId();
        // 权限校验：超级管理员或拥有ROLE:DELETE权限
        if (!permissionCheckUtil.hasPermission(userId, "ROLE:DELETE")) {
            return new Result<>(CodeEnum.NO_PERMISSION);
        }

        if (StrUtils.isEmpty(ids)) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        List<Long> roleIds = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());

        // 批量校验（同单个删除逻辑）
        for (Long roleId : roleIds) {
            SysRoleDTO role = sysRoleService.selectById(roleId);
            if (role == null) {
                return new Result<>(CodeEnum.FAIL, "角色ID=" + roleId + "不存在");
            }
            if ("ADMIN".equals(role.getRoleLogo())) {
                return new Result<>(CodeEnum.FAIL, "不可删除超级管理员角色");
            }
            // 其他校验可参考delete方法
        }

        sysRoleService.deleteBatchIds(roleIds);
        return new Result<>();
    }

    /**
     * 根据ID查询角色（需ROLE:VIEW权限）
     */
    @PostMapping("/get")
    @ApiOperation(value = "根据ID查询角色", notes = "超级管理员或拥有ROLE:VIEW权限的用户可操作")
    @ApiImplicitParam(name = "id", value = "角色ID", required = true, paramType = "query", dataType = "Long")
    public Result<SysRoleDTO> get(@RequestParam("id") Long id) {
        Long userId = getCurrentUserId();
        // 权限校验：超级管理员或拥有ROLE:VIEW权限
        if (!permissionCheckUtil.hasPermission(userId, "ROLE:VIEW")) {
            return new Result<>(CodeEnum.NO_PERMISSION);
        }

        if (id == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        SysRoleDTO dto = sysRoleService.selectById(id);
        return new Result<>(dto);
    }

    /**
     * 角色分页列表（需ROLE:VIEW权限）
     */
    @ApiOperation(value = "角色分页列表", notes = "超级管理员或拥有ROLE:VIEW权限的用户可操作")
    @PostMapping("/queryPageList")
    public Result<Page<SysRoleDTO>> queryPageList(SysRoleBO bo) {
        Long userId = getCurrentUserId();
        // 权限校验：超级管理员或拥有ROLE:VIEW权限
        if (!permissionCheckUtil.hasPermission(userId, "ROLE:VIEW")) {
            return new Result<>(CodeEnum.NO_PERMISSION);
        }

        Wrapper<SysRoleDTO> wrapper = new EntityWrapper<>();
        if (bo.getStatus() != null) {
            wrapper.eq("status", bo.getStatus());
        }
        if (bo.getStartDate() != null) {
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null) {
            wrapper.le("create_time", bo.getEndDate());
        }

        Page<SysRoleDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = sysRoleService.selectPage(page, wrapper);
        return new Result<>(page);
    }

    /**
     * 获取角色权限（需ROLE:VIEW权限）
     */
    @ApiOperation(value = "获取角色权限", notes = "超级管理员或拥有ROLE:VIEW权限的用户可操作")
    @PostMapping("/getRolePermissions")
    @ApiImplicitParam(name = "roleId", value = "角色ID", required = true, paramType = "query", dataType = "Long")
    public Result<List<SysPermissionDTO>> getRolePermissions(@RequestParam("roleId") Long roleId) {
        Long userId = getCurrentUserId();
        // 权限校验：超级管理员或拥有ROLE:VIEW权限
        if (!permissionCheckUtil.hasPermission(userId, "ROLE:VIEW")) {
            return new Result<>(CodeEnum.NO_PERMISSION);
        }

        if (roleId == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        List<SysPermissionDTO> permissions = sysRoleService.getRolePermissions(roleId);
        return new Result<>(permissions);
    }

    /**
     * 分配权限给角色（需ROLE:EDIT权限）
     */
    @ApiOperation(value = "分配权限给角色", notes = "超级管理员或拥有ROLE:EDIT权限的用户可操作")
    @PostMapping("/assignPermissions")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色ID", required = true, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "permissionIds", value = "权限ID列表（逗号分隔）", required = true, paramType = "query", dataType = "String")
    })
    public Result assignPermissions(Long roleId, String permissionIds) {
        Long userId = getCurrentUserId();
        // 权限校验：超级管理员或拥有ROLE:EDIT权限
        if (!permissionCheckUtil.hasPermission(userId, "ROLE:EDIT")) {
            return new Result<>(CodeEnum.NO_PERMISSION);
        }

        if (roleId == null || StrUtils.isEmpty(permissionIds)) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        List<Long> permissionIdList = Arrays.stream(permissionIds.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        boolean flag = sysRoleService.assignPermissions(roleId, permissionIdList);
        return flag ? new Result<>() : new Result<>(CodeEnum.FAIL_100008);
    }
}
